public with sharing class AddUserNationalAttendance {
     public boolean showbutton{get;set;}
     public string orderby{get;set;}
     public boolean showmessage{get;set;}
     public String searchName{get;set;}
     public string str{get;set;}
      public List<SelectOption> options 
    {
        get
        {
            if(options == null)
                options = new List<SelectOption>();
            else
                options.clear();
                
            options.add(new SelectOption('dept__c','部门'));
            options.add(new SelectOption('admintitle__c','行政人员头衔'));
            options.add(new SelectOption('hospital__c,dept__c','医院'));
            options.add(new SelectOption('class1__c','级别1'));
            options.add(new SelectOption('class2__c','级别2'));
            options.add(new SelectOption('class3__c','级别3'));
            return options ;
        }
        set;
    }
     public String idStr{
        get{ 
            return System.currentPageReference().getParameters().get('id');
            }
            set;
     }
     public String msg{
         get;
         set;
     }

    public List<HCPEntry> hcpUser{get;set;}
    public List<NationalAttendee__c> selectedCategories {   
         get {          
                  if (selectedCategories == null) 
                   selectedCategories = new List<NationalAttendee__c>();        
                   return selectedCategories;
            }
                   set;   
     }   
     
     public NationalAttendee__c searchAtt{get;set;}
               
    public PageReference SearchUser()
    {
            id uid=userinfo.getuserid();
           String sql='select id,name,Hospital__c,Dept__c,admintitle__c,class1__c,class2__c,class3__c from HCP__c where name like \'%'+searchName+'%\' and Active__c=true and hospital__r.ownerid = \''+userinfo.getuserid()+'\' and id not in(select HCP__c from NationalAttendee__c where CityNameLists__c=\''+idStr+'\' )';
       if(searchAtt.Hospital__c!=null)
       {
           sql+=' and Hospital__c=\''+searchAtt.Hospital__c+'\'';
       }
       if(orderby!=null){
       sql+=' order by '+orderby;//Dept__c';
       }
       if(hcpUser==null)
       {
              hcpUser=new List<HCPEntry>();
       }
       else
       {
           hcpUser.clear();
       }

       
       for(HCP__c nasql:Database.query('select id,name,Hospital__c,Dept__c,admintitle__c,class1__c,class2__c,class3__c from HCP__c where id  in(select HCP__c from NationalAttendee__c where CityNameLists__c=\''+idStr+'\' )')){
           HCPEntry naen=new HCPEntry(nasql);
           hcpUser.add(naen);
           for(HCPEntry h:hcpuser){
           h.checked=true;}}
       for(HCP__c u:Database.query(sql)){
           HCPEntry entry=new HCPEntry(u);
           hcpUser.add(entry);           
       
       }
       return null;
    }
    
    public AddUserNationalAttendance()
    {
        searchAtt=new NationalAttendee__c();
         idstr=System.currentPageReference().getParameters().get('id'); 
        hcpUser=new list<HCPEntry>();
        searchName='';
        selectedCategories=new List<NationalAttendee__c>();
        searchAtt=new NationalAttendee__c();
        CityNameList__c cnlid=[select id,RegionNameList__c from CityNameList__c where id=:idstr];
        RegionNameList__c rnlid=[select id,hcpeducation__c from RegionNameList__c where id=:cnlid.RegionNameList__c];
        list<hcpeducation__c> hcpautol=[select id,recordtypeid,Hospital__c,date__c from hcpeducation__c where id=:rnlid.hcpeducation__c];    
        orderby='hospital__c,dept__c';
        if(hcpautol.size()>0){
                SearchUser();
                Date Dtoday = Date.today();
                
                if(Dtoday < hcpautol[0].date__c)
                {
                    showbutton=true;
                }              
                else if(Dtoday > hcpautol[0].date__c.addmonths(1).toStartOfMonth()+5 )
                {
         //            showbutton=true;
                }
                
         
           }
    }
    
    public PageReference submitUser()
    {
    
       CityNameList__c cnl2= [Select activitydate__c,Id,Name From CityNameList__c Where id =: idStr ];
       
       if(hcpUser==null){
       id uid=userinfo.getuserid();  
       String sql='select id,name,Hospital__c,Dept__c,admintitle__c,class1__c,class2__c,class3__c from HCP__c where name like \'%'+searchName+'%\' and Active__c=true and hospital__r.ownerid = \''+userinfo.getuserid()+'\' and id not in(select HCP__c from NationalAttendee__c where CityNameLists__c=\''+idStr+'\' )';
       if(searchAtt.Hospital__c!=null)
       {
           sql+=' and Hospital__c=\''+searchAtt.Hospital__c+'\'';
       }
       if(orderby!=null){
       sql+=' order by '+orderby;//Dept__c';
       }
       if(hcpUser==null)
       {
              hcpUser=new List<HCPEntry>();
       }
       else
       {
           hcpUser.clear();
       }
       for(HCP__c nasql:Database.query('select id,name,Hospital__c,Dept__c,admintitle__c,class1__c,class2__c,class3__c from HCP__c where id  in(select HCP__c from NationalAttendee__c where CityNameLists__c=\''+idStr+'\' )')){
           HCPEntry naen=new HCPEntry(nasql);
           hcpUser.add(naen);
           for(HCPEntry h:hcpuser){
           h.checked=true;}}
       for(HCP__c u:Database.query(sql)){
           HCPEntry entry=new HCPEntry(u);
           hcpUser.add(entry);           
       
       }
       return null;
       
       
        }else{ 
          recordtype rt=[select id from recordtype where sobjecttype=:'NationalAttendee__c' and name=:'全国医护人员教育活动'];
          List<citynamelist__c> cityclean=new List<citynamelist__c>();
          cityclean=[select Attendee__c from citynamelist__c where id=:idStr];        
          if(cityclean.size()>0){          
          cityclean[0].attendee__c=0;          
                    
          update cityclean[0];        
          }
        
        CityNameList__c nat=[select RegionNameList__c,RegionNameList__r.HCPEducation__c from CityNameList__c where Id=:idStr];
        
        if(selectedCategories!=null){
            selectedCategories.clear();
        
        List<NationalAttendee__c> nal=new List<NationalAttendee__c>();
        nal=[select id from NationalAttendee__c where CityNameLists__r.Id=:idStr];
            if (nal.size()>0){
            delete nal;
            }
            
        for(HCPEntry en:hcpUser)
        {
            if(en.checked)
            {
               
               NationalAttendee__c mem=new NationalAttendee__c();
               mem.CityNameLists__c=idStr;
               mem.HCP__c=en.hcpList.id;
               mem.RegionNameList__c=nat.RegionNameList__c;
               mem.HCPEducation__c=nat.RegionNameList__r.HCPEducation__c;
               mem.RecordTypeId=rt.id;
               mem.IsAttended__c=true;
              // mem.HCPEducation__c=idStr;
               selectedCategories.add(mem);
               
            }
        }        insert selectedCategories;
        /*
                    list<citynamelist__c> cnl=new list<citynamelist__C>();
                    list<nationalattendee__c> nall=new list<nationalattendee__c>();
                    list<nationalattendee__c> attl=new list<nationalattendee__c>();
                    cnl=[select id,PlannedAttendee__c,Attendee__c from CityNameList__c where Id=:idstr]; //把对应的城市名单找出来，提取ID,PLANNEDATTENDEE
                   if (cnl.size()>0){
                     CityNameList__c cn=cnl[0];
                       nall=[select id,IsAttended__c from NationalAttendee__c where CityNameLists__r.id=:cn.id];//找出所有在这名单下的HCP
                          if(nall.size()>0){
                           Integer i=nall.size();
                           cn.PlannedAttendee__c=i;
                            attl=[select IsAttended__c from NationalAttendee__c where IsAttended__c=:true and CityNameLists__r.id=:cn.id];
                           cn.Attendee__c=attl.size();
                                             }   
          
                            update cn;
                       }
                        list<nationalattendee__c> nalll=[select id from NationalAttendee__c where IsAttended__c=:true and HCPEducation__c=:nat.RegionNameList__r.HCPEducation__c];
                      list<hcpeducation__c>  hcpl=[select id from HCPEducation__c where id=:nat.RegionNameList__r.HCPEducation__c];

                        if(hcpl.size() > 0){
                         HCPEducation__c hcp=hcpl[0];         
                         hcp.LocalActivityAttends__c=nalll.size();
                         update hcp;
                          
                         } */
        }
        
        string callplanid =idStr;    
        pageReference pr = new pageReference('/'+ idStr);           
        pr.setredirect(true);      
        return pr;

        
   
        } 
      }
      
    static testMethod void AddUserNationalAttendanceTest()
    {
         Profile p  = [select id from profile where name=: 'System Administrator'];   //id =:UserInfo.getProfileId()]; 
         User u3 =new User (alias = 'new', email = 'shlia@isoftstone.com', emailencodingkey='UTF-8', lastname = 'Testing', languagelocalekey = 'en_US', localesidkey='en_US', profileid = p.id, timezonesidkey = 'Asia/Shanghai', username='new3@testorg1.com');
        insert u3;
         User u2 =new User (alias = 'new', email = 'shlia@isoftstone.com', emailencodingkey='UTF-8', lastname = 'Testing', languagelocalekey = 'en_US', localesidkey='en_US', profileid = p.id, timezonesidkey = 'Asia/Shanghai', username='new@testorg1.com',managerid=u3.id);
        insert u2;
        User u1 =new User (alias = 'standt', email = 'shlia@isoftstone.com', emailencodingkey='UTF-8', lastname = 'Testing', languagelocalekey = 'en_US', localesidkey='en_US', profileid = p.id, timezonesidkey = 'Asia/Shanghai', username='standarduser@testorg1.com',managerid=u2.id);
        insert u1; 
        
        NationalAttendee__c nat = new NationalAttendee__c();
        
        HCPEducation__c hcpe = new HCPEducation__c();       
        hcpe.date__c = date.Today().addDays(10);
        hcpe.place__c = 'aa';
        insert hcpe;      
        
        Hospital__c hos = new Hospital__c();
        hos.Name = 'aaaaaaaa';
        hos.Nickname__c = 'aaaaaaaaaaa';
        insert hos;
        
        HCP__c hcp= new HCP__c();
        hcp.class1__c = '全国学术带头人(NKOL)';
        hcp.Hospital__c = hos.Id;
        insert hcp;        
   recordtype rgrt=[select id from recordtype where sobjecttype=:'place__c' and name=:'region'];
   Place__c rgl=new  Place__c();
           rgl.name='华北区';
           rgl.recordtypeid=rgrt.id;
           
           insert rgl;
        
           RegionNameList__c rnlc=new RegionNameList__c(ownerid = u1.id,HCPEducation__c=hcpe.id,name='华北区名单',region__c=rgl.id,TargetNo__c=20);
           insert rnlc;
           
           citynamelist__c cnl=new citynamelist__c(ownerid = u1.id,RegionNameList__c=rnlc.id,name='上海',TargetNo__c=20);
           insert cnl;
        System.runAs(u1) {          
        JoinPeople__c jp = new JoinPeople__c ();
           jp.CityNameList__c = cnl.Id;
           jp.User__c = u2.Id;
           insert jp;
       System.runAs(u2) {      
        nat.Hospital__c = hos.Id;
        nat.HCPEducation__c = hcpe.Id;
        nat.HCP__c = hcp.Id;
        
        nat.CityNameLists__c = cnl.Id;
        
        insert nat;           
        
        test.setCurrentPageReference(Page.SearchNationalAttendanceUser);
        System.currentPageReference().getParameters().put('id', cnl.Id); 
  
        
        AddUserNationalAttendance testCase = new AddUserNationalAttendance();
        testCase.SearchUser();
        testCase.submitUser();
        
        testCase.hcpUser = null;
        testCase.submitUser();
        }
        }
    
    }      
      
      
}